var router = require('../common');
var articleMode = require('../../model/articleModel');
var userModule = require('../../model/userMode');
var typeModule = require('../../model/typeMode');
// 新增文章
router.post('/deit', (req, res) => {
    try {
        console.log(req.body);
        let {
            title,
            type,
            author,
            content
        } = req.body;
        if (title == undefined || type == undefined || author == undefined || content == undefined) {
            return res.json({
                code: 1,
                msg: '缺少参数'
            })
        } else if (title == '' || type == '' || author == '' || content == '') {
            return res.json({
                code: 1,
                msg: '缺少参数'
            })
        } else {
            articleMode.create({ ...req.body,
                time: new Date().getTime()
            }).then((data) => {
                res.json({
                    code: 0,
                    msg: data
                })
            })
        }
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})
// 查看文章列表1
router.get('/get', async (req, res) => {
    try {
        let author = req.query.author;
        let pagesize = req.query.pagesize;
        let skip = req.query.skip;
        skip = (skip - 1) * Number(pagesize);
        if (author == '' || author == undefined) {
            return res.json({
                code: 1,
                msg: '参数不完整'
            })
        }
        let findID = await userModule.findOne({
            _id: author
        });
        if (findID) { //如果这个用户存在
            if (findID.isAdmin) { //如果这个是管理员
                // 看全部
                let allData = await articleMode.find({
                    del: {
                        $ne: true
                    }
                }, {
                    __v: 0
                }).populate(['author', 'users']).populate(['type', 'types']).skip(skip).limit(pagesize - 0).sort({
                    _id: -1
                }); //arr1
                let count = await articleMode.find({
                    del: {
                        $ne: true
                    }
                }).countDocuments();
                allData = JSON.parse(JSON.stringify(allData));
                // console.log(allData);
                return res.json({
                    code: 0,
                    count,
                    list: allData
                })
            } else {
                // 看自己的
                let ainData = await articleMode.find({
                    author,
                    del: {
                        $ne: true
                    }
                }, {
                    __v: 0
                }).populate('author type', 'username name').skip(skip).limit(pagesize - 0).sort({
                    _id: -1
                });
                console.log(ainData);
                let count = await articleMode.countDocuments({
                    author,
                    del: {
                        $ne: true
                    }
                });
                ainData = JSON.parse(JSON.stringify(ainData));
                return res.json({
                    code: 0,
                    count,
                    list: ainData
                })
            }
        } else {
            return res.json({
                code: 2,
                msg: '没有这个用户，请前往注册'
            })
        }
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})
// 精确查找文章2
router.get('/detail', (req, res) => {
    try {
        let id = req.query.id;
        if (id == '' || id == undefined) {
            return res.status(404).json({
                code: 1,
                msg: '不传参数我就让你404'
            })
        }
        articleMode.findOne({
                _id: id
            }, {
                del: 0
            }).populate('author', 'username').populate('type', 'name')
            .then((data) => {
                if (data) {
                    res.status(200).json({
                        code: 0,
                        msg: '获取成功',
                        data
                    })
                } else {
                    res.status(200).json({
                        code: 2,
                        msg: '文章不存在'
                    })
                }
            })

    } catch (err) {
        return res.status(500).json({
            code: 9,
            err
        })
    }
})
// 修改文章
router.post('/write', async (req, res) => {
    try {
        let {
            title,
            type,
            content,
            _id
        } = req.body;
        if (_id == undefined || _id == '' || title == '' || title == undefined || type == '' || type == undefined || content == '' || content == undefined) {
            return res.json({
                code: 1,
                msg: '缺少参数'
            })
        }
        let isID = await articleMode.findOne({
            _id
        });
        let isTYPE = await typeModule.findOne({
            _id: type
        });
        console.log(isTYPE);
        if (!isTYPE) {
            return res.json({
                code: 2,
                msg: '分类参数错误'
            })
        }
        if (isID && isTYPE) {
            let data = await articleMode.updateOne({
                _id
            }, {
                $set: {
                    title,
                    type,
                    content,
                    time: new Date().getTime()
                }
            })
            console.log(data);
            res.json({
                code: 0,
                'msg': '更改完成'
            })
        } else {
            res.status(400).json({
                code: 3,
                msg: '系统未找到该文章'
            })
        }
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})
// 删除文章
router.post('/del', async (req, res) => {
    try {
        let {
            uid,
            artid
        } = req.body;
        if (uid == '' || uid == undefined || artid == '' || artid == undefined) {
            return res.json({
                code: 2,
                msg: '缺少参数'
            })
        }
        let userIsAdmin = await userModule.findOne({
            _id: uid
        });
        if (userIsAdmin) {
            let articleData = await articleMode.findOne({
                _id: artid
            });
            if (articleData) { //这篇文章存在
                articleMode.updateOne({
                    _id: artid
                }, {
                    $set: {
                        del: true
                    }
                }).then(() => {
                    return res.json({
                        code: 0,
                        msg: '删除成功'
                    })
                });
            } else {
                return res.json({
                    code: 3,
                    msg: '文章不存在'
                })
            }
        } else {
            return res.json({
                code: 1,
                msg: '违法的进入'
            })
        }
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})
// 根据分类请求文章
router.post('/aaaa', async (req, res) => {
    console.log('??');
    try {
        let type = req.body.type;
        let skip = req.body.skip;
        let limit = req.body.limit;
        skip = (skip - 1) * limit;
        if (type == '' || type == undefined) {
            return res.json({
                code: 1,
                msg: '缺少参数'
            })
        };
        let obj = type == 'home' ? {} : {
            type
        };
        let count = await articleMode.find({ ...obj,
            del: {
                $ne: true
            }
        }, {
            del: 0,
            __v: 0
        }).countDocuments();
        let data = await articleMode.find({ ...obj,
            del: {
                $ne: true
            }
        }, {
            del: 0,
            __v: 0
        }).populate('author', 'username').populate(['type', 'types']).skip(skip).limit(limit - 0).sort({
            _id: -1
        });
        res.json({
            code: 0,
            msg: '请求成功',
            count,
            list: data,
        })
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }

})
// 阅读量设置(进入页面则阅读加1)
router.post('/set/read', async (req, res) => {
    try {
        if (req.body.id == '' || req.body.id == undefined) {
            return res.json({
                code: 1,
                msg: '参数不全'
            })
        }
        console.log(req.body.id);
        let data = await articleMode.updateOne({
            _id: req.body.id
        }, {
            $inc: {
                read: 1
            }
        });
        console.log(data);
        res.json({
            code: 0,
            msg: '添加成功'
        })
    } catch (err) {
        return res.status(500).json({
            code: 9,
            err
        })
    }
})
// 文章添加评论
router.post('/add/comment', async (req, res) => {
    try {
        console.log(req.body);
        let {
            id,
            msg,
            artid
        } = req.body;
        if (id == undefined || id == '' || msg == '' || msg == undefined || artid == '' || artid == undefined) {
            return res.json({
                code: 1,
                msg: '参数不全'
            })
        }
        let temp1 = await userModule.findOne({
            _id: id
        }, {
            password: 0,
            isAdmin: 0,
            __v: 0
        })
        let temp2 = await articleMode.findOne({
            _id: artid
        });
        if (temp1 && temp2) {
            let data = await articleMode.updateOne({
                _id: artid
            }, {
                $push: {
                    discuss: {
                        time: new Date().getTime(),
                        msg,
                        name: id
                    }
                }
            })
            res.json({
                code: 0,
                msg: '添加成功',
                data
            })
        } else {
            res.json({
                code: 2,
                msg: '参数有误'
            })
        }

    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})
// 获取该文章评论信息
router.get('/discuss1', (req, res) => {
    try {
        let id = req.query.id;
        if (id == '' || id == undefined) {
            return res.json({
                code: 1,
                msg: '参数不全'
            })
        }
        articleMode.findOne({
            _id:req.query.id
        }, {
            __: 0
        }).populate('discuss.name','username').then((data) => {
            res.json({
                code: 0,
                data:data.discuss
            })
        })
    } catch (err) {
        res.status(500).json({
            code: 9,
            msg: err
        })
    }
})
module.exports = router;